package com.grouuu.tile
{
	import flash.display.BitmapData;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import starling.core.Starling;
	import starling.display.BlendMode;
	import starling.display.Image;
	import starling.display.MovieClip;
	import starling.textures.Texture;
	
	/**
	 * ...
	 * @author Grouuu
	 */
	public class TileGraphic
	{
		private var _id:int
		private var _img:Image;
		private var _mc:MovieClip;
		private var _bufferImage:Vector.<Image>;
		private var _animated:Boolean = false;
		
		public function TileGraphic(idTile:int, textures:Vector.<Texture>, fps:int = 12)
		{
			init(idTile, textures, fps);
		}
		
		protected function init(idTile:int, textures:Vector.<Texture>, fps:int):void
		{
			_id = idTile;
			
			if (textures.length == 0)
			{
				trace("ERROR : texture null");
				
				return;
			}
			
			if (textures.length == 1)
			{
				try
				{
					_img = new Image(textures[0]);
					_img.blendMode = BlendMode.NONE;
					_img.touchable = false;
				}
				catch (error:Error)
				{
					trace("bad texture");
				}
			}
			else
			{
				_animated = true;
				
				_bufferImage = new Vector.<Image>(textures.length);
				
				_mc = new MovieClip(textures, fps);
				
				_mc.blendMode = BlendMode.NONE;
				_mc.touchable = false;
			}
			
			start();
		}
		
		// CONTROLS ///////////////////////////////////////////////////////////////////////////////
		
		public function nextFrame():void
		{
			// TODO : calculer la frame à afficher avec le getFrameDuration et passer un timer en param
			
			_mc.currentFrame = (_mc.currentFrame == _mc.numFrames - 1) ? 0 : _mc.currentFrame + 1;
		}
		
		public function start():void
		{
			if (_mc)
				_mc.currentFrame = 0;
		}
		
		public function reset():void
		{
			
		}
		
		// GETTER / SETTER ////////////////////////////////////////////////////////////////////////
		
		public function get image():Image
		{
			if (_img)
				return _img;
			
			var currentFrame:int = _mc.currentFrame;
			
			nextFrame();
			
			if (!_bufferImage[currentFrame])
				_bufferImage[currentFrame] = new Image(_mc.texture);
			
			return _bufferImage[currentFrame];
		}
		
		public function get idTile():int
		{
			return _id;
		}
		
		public function get animated():Boolean
		{
			return _animated;
		}
		
		public function get isPassable():Boolean
		{
			return (idTile == 8);
		}
	}
}